import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../Message/SingleChatPage.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import '../WaybillDetails/WaybillDetailsView.dart';
import 'package:platform/platform.dart';
class CancelList extends StatefulWidget {
  const CancelList({super.key});

  @override
  State<CancelList> createState() => _CancelListState();
}

class _CancelListState extends State<CancelList> {
  List dataList=[];
  int pageNum=1;
  bool isLoading =false;
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }


  Future _onRefresh() async {
    getAllOrderListAction();
  }
  @override
  void initState() {
    getAllOrderListAction();
    // TODO: implement initState
    super.initState();
  }

  //获取运单列表
  Future<void> getAllOrderListAction() async {

    NoLoadinggetApiManager.getData(
      context,
      'api/waybill/shipper/waybill/page',
      {
        "pageNum":pageNum,
        "pageSize":20,
        "category":4,
      },
          (responseData) {
        setState(() {

          if(pageNum==1){
            dataList = responseData['data']['records'];
          }else {
            if(responseData['data']['records'].isNotEmpty) {
              dataList.add(responseData['data']['records']);
            }else{
              pageNum=pageNum-1;
            }
          }

        });
      },
    );

  }
  ScrollController _scrollController = ScrollController();
  @override
  void dispose() {
    // 释放控制器资源
    _scrollController.dispose();
    super.dispose();
  }


  void onReachBottom() {
    setState(() {
      pageNum=pageNum+1;
      getAllOrderListAction();

    });
    // 在这里可以执行加载更多数据的逻辑
  }
  //获取IM的uid
  void getUid(String waybillId) async {

  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return
      EasyRefresh(
        header:
        ClassicHeader(
          dragText: '下拉刷新',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '刷新成功',
          noMoreText: '暂无更多',
          failedText: '刷新失败',
          messageText: '刷新时间 %T',
        ),
        footer: ClassicFooter(
          dragText: '加载更多',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '加载成功',
          noMoreText: '暂无更多',
          failedText: '加载失败',
          messageText: '加载时间 %T',
        ),
        onRefresh: _onRefresh,
        onLoad:dataList.length>20*pageNum-1?onReachBottom:null,
        child:    Container(

          color: Color.fromRGBO(248, 248, 248, 1),
    child:
    ListView(

    children: [
    Container(
    height:screenSize.height-180.h,
    child:
        dataList.isEmpty?
    BrnAbnormalStateWidget(
      img: Image.asset(
        'lib/Images/OrderList/找货暂无货源.png',
        scale: 3.0,
      ),
      content: '您的账号暂无已取消运单',
    ):
        ListView.separated(
          shrinkWrap:true,
          itemCount:dataList.length,
          itemBuilder: (BuildContext context, int index) {

            return GestureDetector(
              child:  Container(

                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                padding: EdgeInsets.only(bottom: 11.h,right: 9.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child:Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [

                              BrnTagCustom(
                                tagText:'已取消',
                                backgroundColor: Color.fromRGBO(154, 154, 154, 0.5),
                                textPadding:EdgeInsets.only(left: 8.w,right: 8.w,top: 2.h,bottom: 2.h),
                                fontSize: 12.sp,
                                tagBorderRadius: BorderRadius.only(topLeft: Radius.circular(10),bottomRight: Radius.circular(10) ),
                              ),

                            SizedBox(width:8.w,),
                            if(dataList[index]['category']==1)
                              Image.asset("lib/Images/OrderList/企业标签.png",width: 30.w,height: 18.h,),
                            if(dataList[index]['invoiceType']==1)
                              Image.asset("lib/Images/OrderList/专票标签.png",width:40.w ,height: 18.h,),

                            // BrnTagCustom(
                            //   tagText: "企业",
                            //   textColor: Colors.white,
                            //   backgroundColor: MyColors.themeColor,
                            //   fontWeight: FontWeight.w600,
                            //   fontSize: 12.sp,
                            // ),
                          ],
                        ),
                        if(dataList[index]['riskStatus']==1)
                          Image.asset("lib/Images/OrderList/异常运单.png",width:70.w ,height:20.h,),
                      ],


                    ),
                    // SizedBox(height: 8.h,),


                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SizedBox(width: 10.w,),
                        Column(
                          children: [

                            Image.asset("lib/Images/OrderList/装货点icon.png",width:20.w ,height:20.h,),
                            Image.asset("lib/Images/OrderList/垂直虚线.png",width:13.w ,height:20.h,),
                            if(dataList[index]['goodsInfo']['loadPlaceInfo'].length==2)
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Image.asset("lib/Images/OrderList/装货点icon.png",width:20.w ,height:20.h,),
                                  Image.asset("lib/Images/OrderList/垂直虚线.png",width:18.w ,height:20.h,),
                                ],
                              ),
                            if(dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2)
                              Column(
                                children: [
                                  Image.asset("lib/Images/OrderList/卸货点icon.png",width:20.w ,height:20.h,),
                                  Image.asset("lib/Images/OrderList/垂直虚线.png",width:18.w ,height:20.h,),
                                ],
                              ),
                            Image.asset("lib/Images/OrderList/卸货点icon.png",width:20.w ,height:20.h,),
                          ],
                        ),

                        SizedBox(width: 4.w,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(height: 8.h,),
                            Row(
                              children: [
                                Container(
                                  constraints: BoxConstraints(
                                    maxWidth:170.w, // 限制文本最大宽度
                                  ),
                                  child:
                                  Text(dataList[index]['goodsInfo']['loadPlaceInfo'][0]['city']+" "+dataList[index]['goodsInfo']['loadPlaceInfo'][0]['county'],style: TextStyle(color: Colors.black,overflow: TextOverflow.ellipsis,fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                ),
                                SizedBox(width: 4.w,),
                                Container(
                                  constraints: BoxConstraints(
                                    maxWidth:screenSize.width-220.w, // 限制文本最大宽度
                                  ),
                                  child: Text(dataList[index]['goodsInfo']['loadDay']+dataList[index]['goodsInfo']['loadTime']+"点装货",overflow: TextOverflow.ellipsis,style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                                ),

                              ],
                            ),
                            Container(
                              constraints: BoxConstraints(
                                maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                              ),
                              child: Text(dataList[index]['goodsInfo']['loadPlaceInfo'][0]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),   overflow: TextOverflow.ellipsis,),

                            ),

                            if(dataList[index]['goodsInfo']['loadPlaceInfo'].length==2)
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  SizedBox(height: 8.h,),
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth:170.w, // 限制文本最大宽度
                                    ),
                                    child:Text(dataList[index]['goodsInfo']['loadPlaceInfo'][1]['city']+" "+dataList[index]['goodsInfo']['loadPlaceInfo'][1]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),

                                  ),
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                                    ),
                                    child: Text(dataList[index]['goodsInfo']['loadPlaceInfo'][1]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),

                                  ),
                                ],
                              ),
                            SizedBox(height:8.h,),
                            if(dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2)
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth:170.w, // 限制文本最大宽度
                                    ),
                                    child: Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['city']+" "+dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),

                                  ),
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                                    ),
                                    child: Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                                  ),

                                  SizedBox(height:8.h,),
                                ],
                              ),
                            Row(
                              children:[
                                dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2?
                                Container(
                                    constraints: BoxConstraints(
                                      maxWidth:170.w, // 限制文本最大宽度
                                    ),
                                    child: Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][1]['city']+" "+dataList[index]['goodsInfo']['unloadPlaceInfo'][1]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,)
                                )
                                    :
                                Container(
                                  constraints: BoxConstraints(
                                    maxWidth:170.w, // 限制文本最大宽度
                                  ),
                                  child:  Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['city']+" "+dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['county'],style: TextStyle(color: Colors.black,fontSize: 14.sp,fontWeight: FontWeight.w600),overflow: TextOverflow.ellipsis,),
                                ),

                                SizedBox(width: 4.w,),
                                if (dataList[index]['goodsInfo']['unloadDay'] != null)
                                  Container(
                                    constraints: BoxConstraints(
                                      maxWidth:screenSize.width-220.w, // 限制文本最大宽度
                                    ),
                                    child: Text(dataList[index]['goodsInfo']['unloadDay']+" "+dataList[index]['goodsInfo']['unloadTime']+"点卸货",overflow: TextOverflow.ellipsis,style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),

                                  ) ,                                  ],
                            ),
                            dataList[index]['goodsInfo']['unloadPlaceInfo'].length==2?
                            Container(
                                constraints: BoxConstraints(
                                  maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                                ),
                                child:Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][1]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,)
                            )
                                :
                            Container(
                              constraints: BoxConstraints(
                                maxWidth:screenSize.width-70.w, // 限制文本最大宽度
                              ),
                              child:  Text(dataList[index]['goodsInfo']['unloadPlaceInfo'][0]['address'],style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),overflow: TextOverflow.ellipsis,),
                            ),

                          ],
                        ),

                      ],
                    ),
                    SizedBox(height: 4.h,),
                    Row(
                      children: [
                        SizedBox(width:10.w,),
                        Text( dataList[index]['goodsInfo']['cargoInfo'][0]['cargoName'].toString()+","+dataList[index]['goodsInfo']['cargoInfo'][0]['packageType'].toString(),style: TextStyle(color:MyColors.textColor,fontSize: 13.sp ),),
                        if(dataList[index]['goodsInfo']['cargoInfo'][0]['cargoWeight']!=null)
                          Text( ","+dataList[index]['goodsInfo']['cargoInfo'][0]['cargoWeight'].toString()+"吨",style: TextStyle(color:MyColors.textColor,fontSize: 13.sp ),) ,
                        if(dataList[index]['goodsInfo']['cargoInfo'][0]['cargoVolume']!=null)
                          Text( ","+dataList[index]['goodsInfo']['cargoInfo'][0]['cargoVolume'].toString()+"方",style: TextStyle(color:MyColors.textColor,fontSize: 13.sp ),)
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Container(
                      margin: EdgeInsets.only(left: 20.w,right: 20.w),
                      height: 1.h,
                      color: Color.fromRGBO(245, 243, 243, 1),
                    ),
                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 8.w,),
                            Container(
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child: ClipOval(
                                child: dataList[index]['driverInfo']['avatarPath']!=""&&dataList[index]['driverInfo']['avatarPath']!=null?Image.network(
                                  MyServiceUrl.imgHeader + dataList[index]['driverInfo']['avatarPath'],
                                  width: 36.w,
                                  height: 36.h,
                                  fit: BoxFit.cover,
                                ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w,height: 36.h, fit: BoxFit.cover,),
                              ),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(width: 8.w,),

                                    Text(dataList[index]['driverInfo']['realName']==null?"":dataList[index]['driverInfo']['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),

                                    SizedBox(width: 45.w,),
                                  ],
                                ),

                                Row(
                                  children: [
                                    SizedBox(width: 6.w,),
                                    dataList[index]['vehicleInfo']['vehicleNum']!=null?
                                    Container(
                                      width: 160.w,
                                      child:Text(dataList[index]['vehicleInfo']['vehicleNum']+"丨"+dataList[index]['vehicleInfo']['vehicleLength']+","+dataList[index]['vehicleInfo']['vehicleModel'],style: TextStyle(color:MyColors.textColor,fontSize: 12.sp ,overflow: TextOverflow.ellipsis),),
                                    ):Text("--丨--米",style: TextStyle(color:MyColors.textColor,fontSize: 12.sp ,overflow: TextOverflow.ellipsis),
                                    )],
                                ),

                              ],
                            ),
                          ],
                        ),

                        // SizedBox(width: 40.w,),
                        Row(
                          children: [
                            GestureDetector(
                              child: Image.asset("lib/Images/OrderList/IMicon.png",width: 24.w,height: 24.h,),
                              onTap: (){
                                // Navigator.push(context,
                                // MaterialPageRoute(builder: (context) {
                                //   return SingleChatPage(uid: "4ygqmws2k",
                                //   );
                                // }));
                                getUid(dataList[index]['waybillId']);
                                // speak();
                              },
                            ),
                            SizedBox(width: 8.w,),
                            GestureDetector(
                              child: Image.asset("lib/Images/OrderList/电话联系icon.png",width: 24.w,height: 24.h,),
                              onTap: (){
                                _makePhoneCall(dataList[index]['shprPhoneNum']);
                              },
                            ),
                          ],
                        ),


                      ],
                    ),
                    SizedBox(height:8.h,),
                    Container(
                      margin: EdgeInsets.only(left: 20.w,right: 20.w),
                      height: 1.h,
                      color: Color.fromRGBO(245, 243, 243, 1),
                    ),
                    SizedBox(height:8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        dataList[index]['insuranceStatus']==1?
                        Image.asset("lib/Images/OrderList/保险icon.png",width: 50.w,height: 20.h,):SizedBox(),
                        if(dataList[index]['deposit']!=0)
                          Row(
                            children: [

                              RichText(
                                text:TextSpan(children: [
                                  if(dataList[index]['depositType']!=-1)
                                    TextSpan(
                                        text: messages["订金"],
                                        style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                                  if(dataList[index]['depositType']!=-1)
                                    TextSpan(
                                        text: '¥'+(dataList[index]['deposit']).toString(),
                                        style: TextStyle(fontSize: 11.sp, color: Color.fromRGBO(231, 112, 27, 0.85))),
                                  if(dataList[index]['depositType']!=-1)
                                    TextSpan(
                                        text: dataList[index]['depositStatus']==0?'(待支付)':dataList[index]['depositStatus']==2?"(已退回)":dataList[index]['depositStatus']==2?"(平台监管中)":"(已支付到货主)",
                                        style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                                  TextSpan(
                                      text: messages["运费"],
                                      style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                                  if(dataList[index]['freight']!="0.000")
                                    TextSpan(
                                        text: '¥'+dataList[index]['freight'],
                                        style: TextStyle(fontSize: 11.sp, color: Color.fromRGBO(231, 112, 27, 0.85))),
                                  if(dataList[index]['price']!="0.000"&&dataList[index]['freight']=="0.000")
                                    TextSpan(
                                        text: '¥'+dataList[index]['price'],
                                        style: TextStyle(fontSize: 11.sp, color: Color.fromRGBO(231, 112, 27, 0.85))),
                                  TextSpan(
                                      text: dataList[index]['freightStatus']==-1?'(线下支付)':dataList[index]['freightStatus']==0?'(待支付)':dataList[index]['freightStatus']==1?"(平台监管中)":dataList[index]['freightStatus']==2?"(支付到司机)":"(已退回到货主)",
                                      style: TextStyle(fontSize: 11.sp, color: Colors.black)),
                                ],
                                ),
                              ),
                            ],
                          ),
                      ],
                    ),





                  ],
                ),
              ),
              onTap: () async {
                Navigator.push( context, FadeRoute(page:WaybillDetails(billId: dataList[index]['id'],)));
              },
            );



          },
          separatorBuilder: (context, index) { //自定义分割线
            return   Container(
              height: 8.h,
            );
          },


        ),


    )])

        )
    );


  }
}
